const OSS = require('ali-oss');
const fs = require('fs');
const path = require('path');
const glob = require('glob');

let client = new OSS({
  // LTAI4G1ArobVqqbQqH72JVz3
  // HTv8sQ3c4SpAwBARFbrt6wGPnkjKTH
  accessKeyId: 'LTAI4G1ArobVqqbQqH72JVz3',
  accessKeySecret: 'HTv8sQ3c4SpAwBARFbrt6wGPnkjKTH',
  // stsToken: '',
  bucket: 'voc-license',
  endpoint: 'license.tvoc.site',
  region: 'oss-cn-hangzhou',
  // internal: false,
  cname: true, // 是否支持上传自定义域名，默认false。如果cname为true，endpoint传入自定义域名时，自定义域名需要先同bucket进行绑定。
  // isRequestPay: false,
  // secure: false,
  // timeout: 60,
});

// 1. 查看 Bucket 列表
// async function listBuckets() {
//   try {
//     let result = await client.listBuckets({});
//     console.log(result);
//   } catch (err) {
//     console.log(err);
//   }
// }
// listBuckets().then();

/* 备份根目录 */
const BACKUP_ROOT = 'backup';
const DIST_DIR = 'dist';

// 2 查看文件列表
client.useBucket('voc-license');

/**
 * 列出需备份文件
 * @return {Promise<OSS.ObjectMeta[]>}
 */
const listBackupFile = async () => {
  let result = await client.list(
    {
      'max-keys': 1000,
    },
    {},
  );
  return result.objects.filter((value) => !value.name.startsWith(BACKUP_ROOT));
};

/**
 * 备份文件
 * @param objects 亟需备份文件
 * @param dir 目录 YYYYMMDD_HHmmss
 * @return {Promise<OSS.CopyAndPutMetaResult>}
 */
const backup = async (objects, dir) => {
  return objects.map((o) => {
    const { name } = o;
    return client.copy(`${BACKUP_ROOT}/${dir}/${name}`, name);
  });
};

/**
 * 列出需要上传的文件
 * @return {Promise<string[]>}
 */
const listUploadFile = async () => {
  return glob.sync('**', { cwd: `./${DIST_DIR}` }).filter((s) => fs.statSync(path.join(DIST_DIR, s)).isFile());
};

/**
 * 上传文件
 * @param files
 * @return {Promise<*>}
 */
const upload = async (files) => {
  return files.map((file) => {
    return client.put(file, path.resolve(path.resolve(DIST_DIR, file)));
  });
};

/**
 * 回滚至指定时间戳版本
 * @param timestamp
 */
const rollback = (timestamp) => {};

// listBackupFile()
//   .then((o) => backup(o, '20200825_161530'))
//   .then((s) => {
//     // console.log(s);
//   })
//   .catch((e) => console.error(e));

listUploadFile().then((files) => upload(files));
